# backend/crud/node.py
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from backend.models.node import Node
from backend.schemas.node import NodeCreate, NodeUpdate


async def create_node(db: AsyncSession, data: NodeCreate):
    node = Node(**data.dict())
    db.add(node)
    await db.commit()
    await db.refresh(node)
    return node


async def get_nodes(db: AsyncSession, skip: int = 0, limit: int = 100):
    result = await db.execute(select(Node).offset(skip).limit(limit))
    return result.scalars().all()


async def get_node(db: AsyncSession, node_id: str):
    result = await db.execute(select(Node).where(Node.id == node_id))
    return result.scalar_one_or_none()


async def update_wireguard_info(
        db: AsyncSession,
        node_id: str,
        private_key: str,
        public_key: str,
        endpoint: str
):
    """更新节点的WireGuard信息"""
    result = await db.execute(select(Node).where(Node.id == node_id))
    node = result.scalar_one_or_none()

    if node:
        node.wg_private_key = private_key
        node.wg_public_key = public_key
        node.wg_endpoint = endpoint
        await db.commit()
        await db.refresh(node)

    return node